package com.yangye.otherdemo.semaphoredemo;

import java.util.concurrent.Semaphore;

/**
 * @author yangye
 * @date 2020/08/06
 */
public class SemaphoreDemo {

	public static void main(String[] args) {
		Semaphore semaphore = new Semaphore(2);
		for (int i = 0; i < 5; i++) {
			new Task(semaphore, "线程" + i).start();
		}

	}

	static class Task extends Thread{
		private Semaphore semaphore;

		public Task(Semaphore semaphore, String tName) {
			this.semaphore = semaphore;
			super.setName(tName);
		}
		@Override
		public void run() {
			try {
				semaphore.acquire();
				System.out.println(Thread.currentThread().getName() + "在执行任务");
				Thread.sleep(1000L);
				semaphore.release();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}


}
